package com.hmo.http;

import android.util.Log;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;

public class DownloadResponseBody extends ResponseBody {

    private Response originalResponse;
    private DownloadListener downloadListener;

    public DownloadResponseBody(Response originalResponse, DownloadListener downloadListener){
        this.originalResponse = originalResponse;
        this.downloadListener = downloadListener;
        Log.d("down", "DownloadResponseBody: "+originalResponse.body().contentLength());
    }

    @Override
    public MediaType contentType() {
        return originalResponse.body().contentType();
    }

    @Override
    public long contentLength() {
        return originalResponse.body().contentLength();
    }

    @Override
    public BufferedSource source() {
        return Okio.buffer(new ForwardingSource(originalResponse.body().source()) {
            private long bytesReaded = 0L;
            @Override
            public long read(Buffer sink, long byteCount) {
                long bytesRead = 0;
                try {
                    bytesRead = super.read(sink, byteCount);
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.d("down", "read: "+byteCount);
                }
                bytesReaded += bytesRead == -1 ? 0 : bytesRead;
                if (downloadListener!=null)
                    downloadListener.loading((bytesReaded*100)/originalResponse.body().contentLength());///1024

                return bytesRead;
            }
        });
    }

}
